//
//  EasyTakePicDetailViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/10/29.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "EasyTakePicDetailViewController.h"

#import "InputText4CommentViewController.h"
#import "STSpaceViewController.h"

#import "SSPTabsCell.h"
#import "StwxCommentCell.h"
#import "CommonGoodCell.h"
#import "SSPPublishContentCell.h"

@interface EasyTakePicDetailViewController ()

/// 模型视图
@property (nonatomic, readonly, strong) EasyTakePicDetailViewModel* viewModel;

// UI
@property (nonatomic, weak) UIButton* delBtn;

// IBOutlet
@property (nonatomic, weak) IBOutlet UITableView* currentTableView;
@property (nonatomic, weak) IBOutlet UIButton* shareBtn;
@property (nonatomic, weak) IBOutlet UIButton* zanBtn;
@property (nonatomic, weak) IBOutlet UIButton* commentBtn;
@property (nonatomic, weak) IBOutlet UIView* ctrlView;

@end

@implementation EasyTakePicDetailViewController

@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // hide sys navBar
    self.fd_prefersNavigationBarHidden = NO;
    // 去掉侧滑pop手势
    self.fd_interactivePopDisabled = YES;
    // create subViews
    [self _setupSubViews];
    // deal action
    [self _dealAction];
    /// tableView auto rowHeight
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 100.0f;
    /// tableView rigister  cell
    [self.tableView mh_registerNibCell:[CommonGoodCell class]];
    [self.tableView mh_registerNibCell:[StwxCommentCell class]];
    [self.tableView mh_registerNibCell:[SSPPublishContentCell class]];
    [self.tableView mh_registerNibCell:[SSPTabsCell class]];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    //重置 更新 frame
}

- (void)initData
{
}

- (void)initUI
{
    @weakify(self);
    UIButton* delButton = [UIButton buttonWithType:UIButtonTypeCustom];
    delButton.frame = (CGRect) {0, 0, 32.0f, 44.0f};
    [delButton setTitle:@"删除" forState:UIControlStateNormal];
    [delButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    delButton.titleLabel.font = [UIFont systemFontOfSize:12.0f];
    [delButton addTarget:self action:@selector(_onDelBtn:) forControlEvents:UIControlEventTouchUpInside];
    delButton.hidden = YES;
    self.delBtn = delButton;
    
    UIView* rightView = [[UIView alloc] initWithFrame:(CGRect) {0, 0, 32.0f, 44.0f}];
    [rightView addSubview:delButton];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightView];
}

- (void)_setupSubViews
{
    
}

- (UITableView*)customTableView
{
    return self.currentTableView;
}

#pragma mark - 事件处理
/// 事件处理
- (void)_dealAction
{
    @weakify(self);
    
}

- (void)_onDelBtn:(id)sender
{
    [MBProgressHUD mh_showProgressHUD:@""];
    
    [self.viewModel.delCmd execute:nil];
}

#pragma mark - Override
- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self);
    RACSignal* willAppearSignal = [self rac_signalForSelector:@selector(viewWillAppear:)];
    [[willAppearSignal replay] subscribeNext:^(id x)
     {
         @strongify(self);
         
     }];
    
    RAC(self.delBtn, hidden) = [RACObserve(self.viewModel, isMyself) map:^id(id value) {
        BOOL isMyself = [value boolValue];
        
        return @(!isMyself);
    }];
    
    /// 1. 监听banners的数据变化
    //    [RACObserve(self.viewModel, banners) subscribeNext:^(id x) {
    //        /// 配置数据
    //        @strongify(self);
    //        self.headerView.imageURLStringsGroup = self.viewModel.banners;
    //        self.headerView.hidden = !(self.viewModel.banners.count>0);
    //    }];
    
    /// 2. 处理cell上的点击事件（PS：如果cell的数据不是异步请求的数据，那么就用 RACSubject 代替代理（block） ，否则也可以用 RACCommand代替代理（block），但是建议用 RACSubject，但是RACSubject过于灵活）
    /// cell被点击
    self.viewModel.didSelectCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath *indexPath) {
        @strongify(self);
        // 跳转到活动详情
        //        [self _pushToPublicViewControllerWithTitle:@"活动详情" indexPath:indexPath];
        
        //        [self _push2ExpertInfoVCByIndexPath:indexPath];
        
        return [RACSignal empty];
    }];
    
    [[self.viewModel.sspPublishContentIVM.avatarCommand.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self _push2UserSpaceVC:x];
    }];
    
    RACSignal* shareBtnSignal = [self.shareBtn rac_signalForControlEvents:UIControlEventTouchUpInside];
    [shareBtnSignal subscribeNext:^(id x) {
        
        @strongify(self);
        
        [self _btnListener_share];
    }];
    [[self.viewModel.transmitCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [MBProgressHUD mh_showTips:x];
    }];
    [[self.viewModel.transmitCmd.errors deliverOnMainThread] subscribeNext:^(id x)
    {
        @strongify(self);
        
        NSError* error = x;
        
        if ([error.domain isEqualToString:SUCommandErrorDomain])
        {
            [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
            return;
        }
        [MBProgressHUD mh_showErrorTips:error];
    }];
    
    [RACObserve(self.viewModel, isPraise) subscribeNext:^(id x)
    {
        @strongify(self);
        
        BOOL isPraise = [x boolValue];
        
        self.zanBtn.selected = isPraise;
    }];
    RACSignal* zanBtnSignal = [self.zanBtn rac_signalForControlEvents:UIControlEventTouchUpInside];
    [zanBtnSignal subscribeNext:^(id x) {
        
        @strongify(self);
        
        [self _btnListener_zan];
    }];
    [[self.viewModel.praiseCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self);
         
         [MBProgressHUD mh_showTips:x];
     }];
    [[self.viewModel.praiseCmd.errors deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSError* error = x;
         
         if ([error.domain isEqualToString:SUCommandErrorDomain])
         {
             [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
             return;
         }
         [MBProgressHUD mh_showErrorTips:error];
     }];
    
    RACSignal* commentBtnSignal = [self.commentBtn rac_signalForControlEvents:UIControlEventTouchUpInside];
    [commentBtnSignal subscribeNext:^(id x) {
        
        @strongify(self);
        
        [self _btnListener_comment];
    }];
    [[self.viewModel.commentCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self);
         
         [MBProgressHUD mh_showTips:x];
     }];
    [[self.viewModel.commentCmd.errors deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSError* error = x;
         
         if ([error.domain isEqualToString:SUCommandErrorDomain])
         {
             [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
             return;
         }
         [MBProgressHUD mh_showErrorTips:error];
     }];
    
    // 删除操作
    [[self.viewModel.delCmd.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self);
         
         [MBProgressHUD mh_showTips:x];
         
         [self.navigationController popViewControllerAnimated:YES];
     }];
    [[self.viewModel.delCmd.errors deliverOnMainThread] subscribeNext:^(id x)
     {
         @strongify(self);
         
         NSError* error = x;
         
         if ([error.domain isEqualToString:SUCommandErrorDomain])
         {
             [MBProgressHUD mh_showTips:error.userInfo[SUCommandErrorUserInfoKey]];
             return;
         }
         [MBProgressHUD mh_showErrorTips:error];
     }];
    
    RAC(self.viewModel, tableTabIndex) = RACObserve(self.viewModel.sspTabsCM, tabIndex);
    
    [[self.viewModel.requestRemoteDataCommand.executionSignals.switchToLatest take:1] subscribeNext:^(id x)
    {
        @strongify(self);
        
        [self.tableView reloadData];
    }];
    
    [RACObserve(self.viewModel, isCtrl) subscribeNext:^(id x)
    {
        @strongify(self);
        
        BOOL isCtrl = [x boolValue];
        
        for (NSLayoutConstraint* curConstraint in self.ctrlView.constraints)
        {
            if (curConstraint.firstAttribute == NSLayoutAttributeHeight)
            {
                curConstraint.constant = isCtrl ? 44.0f : 0.0f;
                
                break;
            }
        }
    }];
    
    [[RACObserve(self.viewModel, lastPage) distinctUntilChanged] subscribeNext:^(id x)
    {
        @strongify(self);
        
        self.tableView.mj_footer.hidden = !(self.viewModel.lastPage > self.viewModel.page);
    }];
}

/// config  cell
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
    NSString* cellIdentifier = identifier;
    
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            cellIdentifier = NSStringFromClass([SSPPublishContentCell class]);
        }
        else if (indexPath.row == 1)
        {
            cellIdentifier = NSStringFromClass([SSPTabsCell class]);
        }
    }
    else
    {
        if (self.viewModel.tableTabIndex == 0)
        {
            cellIdentifier = NSStringFromClass([StwxCommentCell class]);
        }
        else
        {
            cellIdentifier = NSStringFromClass([CommonGoodCell class]);
        }
    }
    
    return [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
}

/// config  data
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(NSObject *)object
{
    /// config data (PS：由于MVVM主要是View与数据之间的绑定，但是跟 setViewModel: 差不多啦)
    
    if ([cell isKindOfClass:[SSPPublishContentCell class]])
    {
        SSPPublishContentItemViewModel* curObj = (SSPPublishContentItemViewModel*)object;
        SSPPublishContentCell* curCell = (SSPPublishContentCell*)cell;
        [curCell bindViewModel:curObj];
    }
    else if ([cell isKindOfClass:[SSPTabsCell class]])
    {
        SSPTabsCellModel* curObj = (SSPTabsCellModel*)object;
        SSPTabsCell* curCell = (SSPTabsCell*)cell;
        [curCell bindViewModel:curObj];
    }
    else if ([cell isKindOfClass:[StwxCommentCell class]])
    {
        StwxCommentItemViewModel* curObj = (StwxCommentItemViewModel*)object;
        StwxCommentCell* curCell = (StwxCommentCell*)cell;
        [curCell bindViewModel:curObj];
    }
    else
    {
        CommonGoodCellModel* curObj = (CommonGoodCellModel*)object;
        CommonGoodCell* curCell = (CommonGoodCell*)cell;
        [curCell bindViewModel:curObj];
    }
}

/// 文本内容区域
- (UIEdgeInsets)contentInset
{
    return UIEdgeInsetsZero;
}

#pragma mark - UITableViewDelegate
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    /// 由于使用系统的autoLayout来计算cell的高度，每次滚动时都要重新计算cell的布局以此来获得cell的高度 这样一来性能不好
//    /// 所以笔者采用实现计算好的cell的高度
//
//    return [self.viewModel.dataSource[indexPath.row] cellHeight];
//}

////////////////// 以下为UI代码，不必过多关注 ///////////////////
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    /// FIXED : when data is empty ，the backgroundColor is exist
    return .0001f;
}

#pragma mark - UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    
    // fetch object
    id object = nil;
    
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            object = self.viewModel.sspPublishContentIVM;
        }
        else
        {
            object = self.viewModel.sspTabsCM;
        }
    }
    else
    {
        object = self.viewModel.dataSource[indexPath.section][indexPath.row];
    }
    
    // bind model
    [self configureCell:cell atIndexPath:indexPath withObject:(id)object];
    
    return cell;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}

#pragma mark - Listener
- (void)_btnListener_share
{
    NSLog(@"Stwx Detail Share Btn Click!");
    
    [self.viewModel.transmitCmd execute:nil];
}

- (void)_btnListener_zan
{
    NSLog(@"Stwx Detail Zan Btn Click!");
    
    [self.viewModel.praiseCmd execute:nil];
}

- (void)_btnListener_comment
{
    @weakify(self);
    
    InputText4CommentViewModel* vm = [[InputText4CommentViewModel alloc] initWithParams:@{}];
    vm.publishCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        [self.view resignFirstResponder];
        
        [self.viewModel.commentCmd execute:vm.strText];
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
        {
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }];
    InputText4CommentViewController* vc = [[InputText4CommentViewController alloc] initWithViewModel:vm];
    
    vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    //        modalVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    //        vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    vc.view.backgroundColor = [UIColor clearColor];
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - 跳转
- (void)_push2UserSpaceVC:(NSString*)userID
{
    STSpaceViewModel* vm = [[STSpaceViewModel alloc] initWithParams:@{}];
    vm.userID = userID;
    STSpaceViewController* vc = [[STSpaceViewController alloc] initWithViewModel:vm];
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    MHDealloc;
}

@end
